import React from "react"
import "antd/dist/antd.css"
import store from "./store"
import {
  getInputValueAction,
  getDeleteItemAction,
  getAddItemAction,
  getInitListWithThunk,
  getIniListAction
} from "./store/actionCreators"
import TodoListUI from "./TodoListUI"

class TodoList extends React.Component {
  constructor(props) {
    super(props)
    store.subscribe(this.handleStoreChange)
  }

  state = store.getState()

  componentDidMount() {
    // 获取初始化数据
    // store.dispatch(getInitListWithThunk())
    store.dispatch(getIniListAction())

    // 实现回车提交收入框内容
    document.addEventListener("keydown", (e) => {
      let input = document.querySelector('input')
      if(e.keyCode === 13 && document.activeElement === input){
        this.handleClick()
      }
    })
  }

  render() {
    return (
      <TodoListUI
        inputValue={this.state.inputValue}
        handleInputChange={this.handleInputChange}
        handleClick={this.handleClick}
        handleDeleteItem={this.handleDeleteItem}
        list={this.state.list}
      />
    )
  }

  // 提交输入框的内容到列表中
  handleClick = () => {
    if (this.state.inputValue !== "") {
      const action = getAddItemAction()
      store.dispatch(action)
      this.setState({
        inputValue: ""
      })
    }
  }

  // 改变输入框内容
  handleInputChange = e => {
    console.log(e.target.value)
    const action = getInputValueAction(e.target.value)
    store.dispatch(action)
  }

  // 删除列表项
  handleDeleteItem(index) {
    const action = getDeleteItemAction(index)
    store.dispatch(action)
  }

  handleStoreChange = () => {
    this.setState(store.getState())
  }
}

export default TodoList
